<?php

namespace App\Admin\Controllers;

use App\Models\Cabinet;
use App\Models\CabinetDataSecondBackup;
use App\Http\Controllers\Controller;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
// use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Dcat\Admin\Form;
use Dcat\Admin\Admin;
use Dcat\Admin\Show;
use Illuminate\Http\Request;
use App\Admin\Actions\Batch\DownloadCabinetSecondExcel;

class CabinetDataSecondBackupController extends Controller
{
    public function index(Content $content, $boxId = 0)
    {
        Admin::script(
            <<<JS
    var table = document.getElementById('grid-table');
    table.style.cssText="background-color:#e3e5eb;"
JS            
        );
        $box = Cabinet::find($boxId);
        return $content
            ->body(headmenu($boxId,7))
            ->description($box['name'])
            ->body($this->grid($boxId));
    }

    protected function grid($boxId)
    {
        $optionCabinets = Cabinet::where('pid', $boxId)->where('show', Cabinet::SHOW_YES)->pluck('name', 'id')->toArray();
        $cabinets = Cabinet::where('pid', $boxId)->pluck('id')->toArray();

        $m = CabinetDataSecondBackup::whereIn('cabinet_id', $cabinets)->orderBy('date', 'desc');
        return new Grid($m, function (Grid $grid) use ($optionCabinets) {
            $grid->column('cabinet_id', '设备')->using($optionCabinets);
            $grid->column('date', '日期');
            
            $grid->column('download', '下载')->display(function () {
                $downloadUrl = url(CabinetDataSecondBackup::CATALOGUE.'/'.$this->date.'/'.urlencode($this->name).'.csv');
                return '<a target="_blank" href="'.$downloadUrl.'"><i class="fa fa-download"></i></a>';
            });

            $grid->filter(function (Grid\Filter $filter) use ($optionCabinets) {
                $filter->panel();
                $filter->equal('cabinet_id', '设备')->select($optionCabinets);
                $filter->date('date', '日期');
            });

            $grid->disableBatchDelete();
            $grid->batchActions([
                new DownloadCabinetSecondExcel('批量下载')
            ]);

            $grid->disableCreateButton();
            $grid->disableActions();
        });
    }

    public function destroy($boxId, $id)
    {
        return $this->form()->destroy($id);
    }
}